﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Services;
using Catering.View_Operaction;
using System.Text;
using System.IO;

namespace Catering.Catering_Page.richang
{
    public partial class cbsgl : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Ajax.Utility.RegisterTypeForAjax(typeof(cbsgl));
            if (!IsPostBack)
            {
                Txt_data.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy/MM/dd'})");
                Txt_data.Text = DateTime.Now.ToString("yyyy-MM-dd");
                this.LoadRep();
                this.LoadDrop();
            }
        }

        //公用的DropDownList绑定方法
        public void DropBind(DropDownList drop, DataTable dt, string strValue, string strText)
        {
            drop.Items.Clear();
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ListItem item = new ListItem();
                    item.Text = dt.Rows[i][strText].ToString();
                    item.Value = dt.Rows[i][strValue].ToString();
                    drop.Items.Add(item);
                }
            }
        }

        protected void LoadDrop()
        {
            if (Session["PersonnelID"] != null)
            {
                string userid = Session["PersonnelID"].ToString();
                int companyid = 0;
                int groupid = 0;
                int classid = 0;
                bool isAdmin = false;
                Bind_Data_to_Controls.GetCompanyByCurrentUser(userid, out companyid, out groupid, out classid, out isAdmin);
                DataTable dt_zyq = new Catering_Rules.OperationArea().GetAllListByCompanyID(companyid).Tables[0];
                this.DropBind(this.txt_info_zyq, dt_zyq, "id", "AreaName");
            }
        }

        protected void LoadRep()
        {
            DataTable dt_Contractor = new Catering_Rules.Contractor().GetAllList().Tables[0];
            this.Rep_cbs.DataSource = dt_Contractor;
            this.Rep_cbs.DataBind();
        }

        //删除承包商
        [WebMethod]
        public static string Del_Contractor(string strid)
        {
            return new Catering_Rules.Contractor().Delete(Convert.ToInt32(strid)) ? "OK" : "NO";
        }

        //添加承包商
        [WebMethod]
        public static string Add_Contractor(string CName, string LinkId, string Tel, string Add, string State, string Description)
        {
            Catering_Model.Contractor md = new Catering_Model.Contractor();
            md.CName = CName;
            md.LinkId = LinkId;
            md.Tel = Tel;
            md.Address = Add;
            md.State = State;
            md.Description = Description;
            new Catering_Rules.Contractor().Add(md);
            return "OK";
        }

        //获取承包商信息
        [Ajax.AjaxMethod]
        public DataTable Get_Contractor(string strid, string time)
        {
            DateTime date = DateTime.Now;
            if (!string.IsNullOrEmpty(time)) DateTime.TryParse(time, out date);

            DataTable dt = new DataTable();
            dt.Columns.Add("CName", typeof(string));
            dt.Columns.Add("LinkId", typeof(string));
            dt.Columns.Add("Tel", typeof(string));
            dt.Columns.Add("Address", typeof(string));
            dt.Columns.Add("State", typeof(string));
            dt.Columns.Add("ContentDesc", typeof(string));
            dt.Columns.Add("Description", typeof(string));
            DataTable tmepdt = new Catering_Rules.Contractor().GetList("id=" + strid).Tables[0];

            if (tmepdt != null && tmepdt.Rows.Count > 0)
            {
                for (int i = 0; i < tmepdt.Rows.Count; i++)
                {
                    DataRow dr = dt.NewRow();
                    int id = Convert.ToInt32(tmepdt.Rows[i]["ID"].ToString());
                    string name = tmepdt.Rows[i]["CName"].ToString();
                    string linkid = tmepdt.Rows[i]["LinkId"].ToString();
                    string Tel = tmepdt.Rows[i]["Tel"].ToString();
                    string Add = tmepdt.Rows[i]["Address"].ToString();
                    string Description = tmepdt.Rows[i]["Description"].ToString();

                    string state = "未作业";
                    string content = "";

                    //Catering_Model.ContractorDailyMangement md = new Catering_Rules.ContractorDailyMangement().GetModel(" WHERE CID=" + id + " AND Year(DTime)=" + date.Year + " AND Month(DTime)=" + date.Month + " AND Day(DTime)=" + date.Day);
                    //if (md != null)
                    //{
                    //    state = "作业中";
                    //    content = md.ContentDesc;
                    //    Catering_Model.ClassInfo classinfo = new Catering_Rules.ClassInfo().GetModel(md.ClassID);
                    //    if (classinfo != null)
                    //    {
                    //        content = classinfo.CName + "：" + content;
                    //    }
                    //}

                    DataTable dt_cdm = new Catering_Rules.ContractorDailyMangement().GetList(" CID=" + id + " AND Year(DTime)=" + date.Year + " AND Month(DTime)=" + date.Month + " AND Day(DTime)=" + date.Day).Tables[0];
                    if (dt_cdm != null && dt_cdm.Rows.Count > 0)
                    {
                        for (int j = 0; j < dt_cdm.Rows.Count; j++)
                        {
                            string content1 = dt_cdm.Rows[j]["ContentDesc"].ToString();
                            int classid = Convert.ToInt32(dt_cdm.Rows[j]["ClassID"].ToString());
                            if (classid > 0)
                            {
                                Catering_Model.ClassInfo classinfo = new Catering_Rules.ClassInfo().GetModel(classid);
                                if (classinfo != null) content1 = classinfo.CName + "：" + content1;
                            }
                            content1 += "\n";
                            content += content1;
                        }
                        dt_cdm.Dispose();
                    }

                    dr["CName"] = name;
                    dr["LinkId"] = linkid;
                    dr["Tel"] = Tel;
                    dr["Address"] = Add;
                    dr["State"] = state;
                    dr["ContentDesc"] = content;
                    dr["Description"] = Description;
                    dt.Rows.Add(dr);
                }
                tmepdt.Dispose();
            }
            return dt;
        }

        //获取承包商详细信息
        [Ajax.AjaxMethod]
        public DataTable Get_ContractorInfo(string strid)
        {
            return new Catering_Rules.ContractorInfo().GetList("CID=" + strid).Tables[0];
        }

        //修改承包商
        [WebMethod]
        public static string Edit_Contractor(string cid, string CName, string LinkId, string Tel, string Add, string State, string Description)
        {
            Catering_Model.Contractor md = new Catering_Model.Contractor();
            md.id = Convert.ToInt32(cid);
            md.CName = CName;
            md.LinkId = LinkId;
            md.Tel = Tel;
            md.Address = Add;
            md.State = State;
            md.Description = Description;
            return new Catering_Rules.Contractor().Update(md) ? "OK" : "NO";
        }

        //添加和修改承包商详细信息
        [WebMethod]
        public static string Edit_ContractorInfo(string CID, string CName, string GroupID, string CardNo, string JobCard, string Effective, string Tel, string EffectiveArea, string EffectiveEnd)
        {
            new Catering_Rules.ContractorInfo().DeleteList("CID=" + CID);
            Catering_Model.ContractorInfo md = new Catering_Model.ContractorInfo();
            md.CID = Convert.ToInt32(CID);
            md.CName = CName;
            md.GroupID = GroupID;
            md.CardNo = CardNo;
            md.JobCard = JobCard;
            md.Effective = Effective;
            md.Tel = Tel;
            //md.EffectiveArea = EffectiveArea;---------------------------------------------------------------------
            //md.EffectiveEnd = EffectiveEnd;-----------------------------------------------------------------------
            new Catering_Rules.ContractorInfo().Add(md);
            return "OK";
        }

        //导出
        protected void but_Excel_Click(object sender, EventArgs e)
        {
            DateTime date = DateTime.Now;
            if (!string.IsNullOrEmpty(this.Txt_data.Text.ToString())) DateTime.TryParse(this.Txt_data.Text.ToString(), out date);
            DataTable dt = new Catering_Rules.Contractor().GetList("CName like '%" + this.Txt_Cname.Text.Trim() + "%'").Tables[0];

            Microsoft.Office.Interop.Excel.Application excel1 = null;
            Microsoft.Office.Interop.Excel._Worksheet ws = null;
            Microsoft.Office.Interop.Excel.Range canbie = null;
            string stick = DateTime.Now.Ticks.ToString();

            try
            {
                excel1 = new Microsoft.Office.Interop.Excel.Application();
                excel1.Application.Workbooks.Add(true);//引用Excel工作簿
                //Microsoft.Office.Interop.Excel._Worksheet ws = new Microsoft.Office.Interop.Excel.WorksheetClass();
                ws = new Microsoft.Office.Interop.Excel.WorksheetClass();
                ws = (Microsoft.Office.Interop.Excel._Worksheet)excel1.ActiveSheet;//获取当前活动工作薄
                //Microsoft.Office.Interop.Excel.Range canbie;//创建Range操作一行作为标题
                excel1.Visible = false;

                #region  表头


                canbie = ws.get_Range(ws.Cells[1, 1], ws.Cells[1, 8]);
                canbie.MergeCells = true;//合并单元格
                canbie.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//居中
                canbie.Font.Bold = 2;
                ws.Cells[1, 1] = "承包商管理清单";

                #endregion

                #region 第一行标题
                ws.Cells[2, 1] = "序号";
                ws.Cells[2, 2] = "承包商名称";
                ws.Cells[2, 3] = "联系人";
                ws.Cells[2, 4] = "联系电话";
                ws.Cells[2, 5] = "地址";
                ws.Cells[2, 6] = "状态";
                ws.Cells[2, 7] = "工作量统计";
                ws.Cells[2, 8] = "评价或说明";


                #endregion

                #region 内容

                int canbiehangshu = 3;//行数
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        int id = Convert.ToInt32(dt.Rows[i]["ID"].ToString());
                        string name = dt.Rows[i]["CName"].ToString();
                        string linkid = dt.Rows[i]["LinkId"].ToString();
                        string Tel = dt.Rows[i]["Tel"].ToString();
                        string Add = dt.Rows[i]["Address"].ToString();
                        string Description = dt.Rows[i]["Description"].ToString();

                        string state = "未作业";
                        string content = "";

                        DataTable dt_cdm = new Catering_Rules.ContractorDailyMangement().GetList(" CID=" + id + " AND Year(DTime)=" + date.Year + " AND Month(DTime)=" + date.Month + " AND Day(DTime)=" + date.Day).Tables[0];
                        if (dt_cdm != null && dt_cdm.Rows.Count > 0)
                        {
                            for (int j = 0; j < dt_cdm.Rows.Count; j++)
                            {
                                string content1 = dt_cdm.Rows[j]["ContentDesc"].ToString();
                                int classid = Convert.ToInt32(dt_cdm.Rows[j]["ClassID"].ToString());
                                if (content1.Length > 10) content1 = content1.Substring(0, 10) + "…";
                                if (classid > 0)
                                {
                                    Catering_Model.ClassInfo classinfo = new Catering_Rules.ClassInfo().GetModel(classid);
                                    if (classinfo != null) content1 = classinfo.CName + "：" + content1;
                                }
                                content1 += "<br/>";
                                content += content1;
                            }
                            dt_cdm.Dispose();
                        }

                        ws.Cells[canbiehangshu, 1] = (i + 1);
                        ws.Cells[canbiehangshu, 2] = name;
                        ws.Cells[canbiehangshu, 3] = linkid;
                        ws.Cells[canbiehangshu, 4] = Tel;
                        ws.Cells[canbiehangshu, 5] = Add;
                        ws.Cells[canbiehangshu, 6] = state;
                        ws.Cells[canbiehangshu, 7] = content;
                        ws.Cells[canbiehangshu, 8] = Description;
                        canbiehangshu++;
                    }
                    dt.Dispose();
                }
                ws.Cells.EntireColumn.AutoFit();
                canbie = ws.get_Range(ws.Cells[2, 1], ws.Cells[canbiehangshu - 1, 8]);
                canbie.Borders.LineStyle = 1;

                #endregion

                if (!Directory.Exists(Server.MapPath("../../xls_template"))) Directory.CreateDirectory(Server.MapPath("../../xls_template"));
                ws.SaveAs(Server.MapPath("../../xls_template") + "\\" + stick + ".xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlAddIn8);
            }
            finally
            {
                if (excel1 != null)
                {
                    if (ws != null)
                    {
                        if (canbie != null)
                        {
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(canbie);
                            canbie = null;

                        }
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
                        ws = null;
                    }
                    excel1.Application.Workbooks.Close();
                    excel1.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel1);
                    Toolss.KillExcel(excel1);
                    excel1 = null;
                    GC.Collect();
                }
            }

            #region 发送

            try
            {
                string path = Server.MapPath("../../xls_template") + "\\" + stick + ".xls";
                System.IO.FileInfo file = new System.IO.FileInfo(path);
                Response.Clear();
                Response.Charset = "GB2312";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                // 添加头信息，,弹出另存为窗口  
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
                //让浏览器头显示下载信息  
                Response.AddHeader("Content-Length", file.Length.ToString());
                // 指定返回一个不能被客户端读取的流，下载  
                Response.ContentType = "application/ms-excel";
                //把文件流下载到客户端  
                Response.WriteFile(file.FullName);
                // 停止页面的执行
                Response.End();

            #endregion
            }
            catch
            {
            }
        }

        //根据条件进行查询
        protected void btn_Search_Click(object sender, EventArgs e)
        {
            DataTable dt_Contractor = new Catering_Rules.Contractor().GetList("CName like '%" + this.Txt_Cname.Text.Trim() + "%'").Tables[0];
            this.Rep_cbs.DataSource = dt_Contractor;
            this.Rep_cbs.DataBind();
        }

        public string GetState(string id, string time)
        {
            DateTime date = DateTime.Now;
            DateTime.TryParse(time, out date);
            int count = new Catering_Rules.ContractorDailyMangement().GetCount(" WHERE CID=" + id + " AND Year(DTime)=" + date.Year + " AND Month(DTime)=" + date.Month + " AND Day(DTime)=" + date.Day);
            if (count > 0) return "作业中"; else return "未作业";
        }

        public string GetContent(string id, string time)
        {
            DateTime date = DateTime.Now;
            if (!string.IsNullOrEmpty(time)) DateTime.TryParse(time, out date);

            #region old

            //Catering_Model.ContractorDailyMangement md = new Catering_Rules.ContractorDailyMangement().GetModel(" WHERE CID=" + id + " AND Year(DTime)=" + date.Year + " AND Month(DTime)=" + date.Month + " AND Day(DTime)=" + date.Day);
            //if (md != null)
            //{
            //    string content = "";
            //    if (md.ContentDesc.Length > 10)
            //    {
            //        content = md.ContentDesc.Substring(0, 10) + "…";
            //    }
            //    else
            //    {
            //        content = md.ContentDesc;
            //    }
            //    Catering_Model.ClassInfo classinfo = new Catering_Rules.ClassInfo().GetModel(md.ClassID);
            //    if (classinfo != null)
            //    {
            //        content = classinfo.CName + "：" + content;
            //    }
            //    return content;
            //}

            #endregion

            StringBuilder result = new StringBuilder("");
            DataTable dt = new Catering_Rules.ContractorDailyMangement().GetList(" CID=" + id + " AND Year(DTime)=" + date.Year + " AND Month(DTime)=" + date.Month + " AND Day(DTime)=" + date.Day).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string content = dt.Rows[i]["ContentDesc"].ToString();
                    int classid = Convert.ToInt32(dt.Rows[i]["ClassID"].ToString());
                    if (content.Length > 10) content = content.Substring(0, 10) + "…";
                    if (classid > 0)
                    {
                        Catering_Model.ClassInfo classinfo = new Catering_Rules.ClassInfo().GetModel(classid);
                        if (classinfo != null) content = classinfo.CName + "：" + content;
                    }
                    content += "<br/>";
                    result.Append(content);
                }
                dt.Dispose();
                string temstr = result.ToString();
                if (!string.IsNullOrEmpty(temstr))
                {
                    temstr = temstr.Substring(0, temstr.Length - 5);
                }
                return temstr;
            }
            return "";
        }

        protected void Txt_data_TextChanged(object sender, EventArgs e)
        {
            btn_Search_Click(null, null);
        }
    }
}